<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="20%">
    <div v-if="formType === 'bindPhone' || (formType === 'changePhone' && verifyStatus)">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules">
        <el-form-item prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" @change="checkAccount" />
        </el-form-item>
        <el-form-item prop="code">
          <div style="display: flex;flex-wrap: nowrap;">
            <el-input v-model="formData.code" placeholder="请输入验证码" style="width: 220px;" />
            <el-button type="primary" :disabled="isSending || countdown > 0" @click="sendCode"
              style="margin-left: 10%;">
              {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="formType === 'changePhone' && verifyStatus === false">
      <div class="check-user-text">为了保护账号安全，请使用{{ formattingPhone(phoneNumber) }}验证身份</div>
      <div style="display: flex;flex-wrap: nowrap;">
        <el-input v-model="verifycode" placeholder="请输入验证码" style="width: 220px;" />
        <el-button type="primary" :disabled="verifySending || countdown > 0" @click="sendCode1"
          style="margin-left: 10%;">
          {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
        </el-button>
      </div>
    </div>
    <div v-if="formType === 'bindThird' || formType === 'unBindThird'" style="text-align: center;">
      <div id="login_container" style="height: 200px;display: flex;justify-content: center;"></div>
      <span v-if="formType === 'bindThird'" style="font-size: 16px;">请使用微信扫码完成绑定</span>
      <span v-if="formType === 'unBindThird'" style="font-size: 16px;">请使用微信扫码完成解绑</span>
    </div>
    <template #footer>
      <div v-if="formType === 'bindPhone' || (formType === 'changePhone' && verifyStatus)">
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
      <el-button v-if="formType === 'changePhone' && verifyStatus === false" :disabled="formLoading" type="primary"
        @click="toNext">下一步</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as ProfileApi from '@/api/system/user/profile'
import { FormRules } from 'element-plus'
import { nextTick } from 'vue'
import { getUserId } from '@/utils/auth'
import WxLogin from '../wxLogin.js'
defineOptions({ name: 'UserInfoDialog' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  phone: '',
  code: ''
})
const formRules = reactive<FormRules>({
  phone: [
    {
      validator: async (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入手机号码'))
        }
        const regex = /^1[3-9]\d{9}$/;
        if (!regex.test(value)) {
          callback(new Error('手机号码格式不正确'));
        }
        const data = await ProfileApi.checkAccount({ accountType: "Phone", account: value })
        if (data === "账号存在") {
          callback(new Error('该手机号已被绑定'))
        } else {
          isSending.value = false
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const isSending = ref(true)
const verifycode = ref('')
const verifySending = ref(false)
const countdown = ref(0)
const phoneNumber = ref('')
const verifyStatus = ref(false)
/** 打开弹窗 */
const open = async (type: string, phone?: any) => {
  dialogVisible.value = true
  formType.value = type
  phoneNumber.value = phone
  if (type === 'bindPhone') {
    dialogTitle.value = '绑定手机号'
  } else if (type === 'changePhone') {
    dialogTitle.value = '更换手机号'
  } else if (type === 'bindThird') {
    dialogTitle.value = '绑定微信'
    nextTick(() => {
      new WxLogin({
        self_redirect: true,
        id: "login_container",
        appid: 'wxa09b43f4683a8c30',
        scope: "snsapi_login",
        redirect_uri: "https://api.geovisearth.com/passport/auth/bindWechat",
        state: undefined,
        login_type: 'jssdk',
        href: 'data:text/css;base64,aHRtbCwgYm9keSB7DQogICAgd2lkdGg6IDEwMCU7DQogICAgaGVpZ2h0OiAxMDAlOw0KICAgIG1hcmdpbjogMHB4Ow0KICAgIHBhZGRpbmc6IDBweDsNCn0NCi50aXRsZSB7DQogICAgZGlzcGxheTogbm9uZTsNCn0NCi5pbmZvIHsNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0KLndycF9jb2RlIHsNCiAgICB3aWR0aDogMTAwdnc7DQogICAgaGVpZ2h0OiAxMDB2aDsNCiAgICBtYXgtd2lkdGg6IDE4NnB4IWltcG9ydGFudDsNCiAgICBtYXJnaW46IDAgYXV0bzsNCiAgICBvdmVyZmxvdzogaGlkZGVuOw0KfQ0KLnFyY29kZSB7DQogICAgd2lkdGg6IDEwMCUhaW1wb3J0YW50Ow0KICAgIGhlaWdodDogMTAwJTsNCiAgICBtYXgtaGVpZ2h0OiAxODhweCFpbXBvcnRhbnQ7DQogICAgb2JqZWN0LWZpdDogY29udGFpbjsNCiAgICBib3JkZXI6IG5vbmUhaW1wb3J0YW50Ow0KICAgIG1hcmdpbi10b3A6IDBweCFpbXBvcnRhbnQ7DQp9'
      });
    })
    window.onmessage = async (e) => {
      dialogVisible.value = false
      let data = await ProfileApi.bindThird({
        thirdID: e.data.user.unionid,
        platform: '1',
        extra: {}
      })
      if (data !== null) {
        message.success('绑定成功')
        emit('success')
        ProfileApi.updateUser({ weixinAccount: e.data.user.unionid, id: getUserId() })
      }
    }

  } else if (type === 'unBindThird') {
    dialogTitle.value = '解绑微信'
    nextTick(() => {
      new WxLogin({
        self_redirect: true,
        id: "login_container",
        appid: 'wxa09b43f4683a8c30',
        scope: "snsapi_login",
        redirect_uri: "https://api.geovisearth.com/passport/auth/bindWechat",
        state: undefined,
        login_type: 'jssdk',
        href: 'data:text/css;base64,aHRtbCwgYm9keSB7DQogICAgd2lkdGg6IDEwMCU7DQogICAgaGVpZ2h0OiAxMDAlOw0KICAgIG1hcmdpbjogMHB4Ow0KICAgIHBhZGRpbmc6IDBweDsNCn0NCi50aXRsZSB7DQogICAgZGlzcGxheTogbm9uZTsNCn0NCi5pbmZvIHsNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0KLndycF9jb2RlIHsNCiAgICB3aWR0aDogMTAwdnc7DQogICAgaGVpZ2h0OiAxMDB2aDsNCiAgICBtYXgtd2lkdGg6IDE4NnB4IWltcG9ydGFudDsNCiAgICBtYXJnaW46IDAgYXV0bzsNCiAgICBvdmVyZmxvdzogaGlkZGVuOw0KfQ0KLnFyY29kZSB7DQogICAgd2lkdGg6IDEwMCUhaW1wb3J0YW50Ow0KICAgIGhlaWdodDogMTAwJTsNCiAgICBtYXgtaGVpZ2h0OiAxODhweCFpbXBvcnRhbnQ7DQogICAgb2JqZWN0LWZpdDogY29udGFpbjsNCiAgICBib3JkZXI6IG5vbmUhaW1wb3J0YW50Ow0KICAgIG1hcmdpbi10b3A6IDBweCFpbXBvcnRhbnQ7DQp9'
      });
    })
    window.onmessage = async (e) => {
      dialogVisible.value = false
      let data = await ProfileApi.unBindThird({
        thirdID: e.data.user.unionid,
        platform: '1',
        extra: {}
      })
      if (data !== null) {
        message.success('解绑成功')
        emit('success')
        ProfileApi.updateUser({ weixinAccount: '', id: getUserId() })
      }
    }
  }
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'bindPhone') {
      let data = await ProfileApi.bindPhone(formData.value)
      if (data !== null) {
        countdown.value = 0
        message.success('绑定成功')
        ProfileApi.updateUser({ mobile: formData.value.phone, id: getUserId() })
      }
    } else if (formType.value === 'changePhone') {
      let data = await ProfileApi.changePhone({ phone: phoneNumber.value, code: verifycode.value, newPhone: formData.value.phone, newCode: formData.value.code })
      if (data !== null) {
        countdown.value = 0
        message.success('更换成功')
        ProfileApi.updateUser({ mobile: formData.value.phone, id: getUserId() })
      }
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const toNext = async () => {
  if (!verifycode.value) {
    message.error('未填写验证码')
    return
  }
  let data = await ProfileApi.verifyPhoneCode({ phone: phoneNumber.value, code: verifycode.value })
  if (data !== null) {
    verifyStatus.value = true
    countdown.value = 0
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    phone: '',
    code: ''
  }
  formRef.value?.resetFields()
}

const checkAccount = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
}

const sendCode = async () => {
  if (!formData.value.phone) {
    message.error('未填写手机号')
    return
  }
  const data = await ProfileApi.sendSmsCode({ appkey: 'E21219DF60CD41EDB2DFF30B04FF7C6E', phone: formData.value.phone })
  if (data === '短信验证码发送成功,有效期:300s') {
    isSending.value = false
    startCountdown();
  }
}

const sendCode1 = async () => {
  const data = await ProfileApi.sendSmsCode({ appkey: 'E21219DF60CD41EDB2DFF30B04FF7C6E', phone: phoneNumber.value })
  if (data === '短信验证码发送成功,有效期:300s') {
    isSending.value = false
    startCountdown();
  }
}

const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
}

/** 隐藏手机号 */
const formattingPhone = (cellValue) => {
  if (Number(cellValue) && String(cellValue).length === 11) {
    var mobile = String(cellValue);
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    return mobile.replace(reg, "$1****$2");
  } else {
    return cellValue;
  }
}


</script>

<style>
.check-user-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 5%;
}
</style>